<?php

class AuctionLotsController extends Admin_Controller {

    const NO_ERRORS = 0x00;
    const ERROR_FILE_TYPE = 0x01;
    const ERROR_EXCHANGE_FILE = 0x02;
    const UPLOAD_ERROR = 0x03;
    const DB_ERROR = 0x04;
    
    public function init() {
        parent::init();
        $this->setActiveCat(983);
        $this->_table_lots = new Admin_Table_Auction_Lots();
        $this->_table_auction = new Admin_Table_Auction_Auction();
    }

    public function indexAction(){
 
         
        
        
        $form = new Llib_Form($this->_request);
        $filters = array();
        
        if ($this->_request->isPost()) {
        	$filters['by_cad_num'] = $this->_request->getParam('by_cad_num', '');
        	$filters['by_status'] = $this->_request->getParam('by_status', '');
                $filters['by_approved'] = $this->_request->getParam('by_approved', '');
                $filters['by_gone'] = $this->_request->getParam('by_gone', '');
        }

        $filters = $this->SessionVarsEx($filters, array('by_cad_num','by_status','by_approved' => '-1','by_gone' => '-1'), $this->_request->getParam('reset', false));
        
        $filters['is_approved'] = $this->_table_lots->GetApprovedList($filters['by_approved']);
        $filters['is_gone'] = $this->_table_lots->GetGoneList($filters['by_gone']);
        
        if (isset($this->_user->koatuu) && $this->_user->koatuu != 0 ) $filters['cad_num_koatuu']=$this->_user->koatuu;
        $error = intval($this->_request->getParam('error'));
        
        if ($error) {
            switch ($error) {
                case AuctionController::ERROR_EXCHANGE_FILE:
                    $form->SetError("Обмінний файл містить помилки.");
                    break;
                case AuctionController::ERROR_FILE_TYPE:
                    $form->SetError("Не вірний формат файлу.");
                    break;
                case AuctionController::UPLOAD_ERROR:
                    $form->SetError("Виникла помилка під час завантаження обмінного файлу.");
                    break;
                case AuctionController::DB_ERROR:
                    $form->SetError("Не вдалося створити лот. Виникла помилка бази даних.");
                    break;
                default:
                    $form->SetError("Виникла помилка під час створення лоту.");
                    break;
            }
        }

        $lclm = new Llib_List($this->_request, $this->_sess);
        $lclm->AddParams(array(
            'checkboxes' => false,
        	//'link_fields'=>array('cad_num'),
            'link' => "/" . $this->controller . "/view/"
        ));
        $lclm->AddColumn('№ Лоту', 'id', array('width' => '5%', 'sort' => 1));
        $lclm->AddColumn('Кадастровий номер', 'cad_num', array('width' => '10%', 'sort' => 1));
        $lclm->AddColumn('Площа (га)', 'area', array('width' => '5%', 'sort' => 1));
        $lclm->AddColumn('Адреса', 'parcel_address', array('width' => '30%', 'sort' => 1));
        $lclm->AddColumn('Вид цільового призначення земель (згідно класифікатору)', 'purpose', array('width' => '30%', 'sort' => 0));  // Цільове призначення 
        $lclm->AddColumn('', 'attantion', array('width' => '1%', 'sort' => 0));        
        $lclm->AddColumn('Статус', 'status', array('width' => '20%', 'sort' => 1));
        $lclm->AddColumn('', 'is_published', array('width' => '1%', 'sort' => 1));
        $data = $this->_table_lots->getDataList($lclm->page, $lclm->s, $lclm->pager_count, $filters);
      
#------------------- В колонке «Цільове призначення» код заменить на его расшифровку текстом ----------------------------------------------------   
// ----------  Цільове призначення переим. в  Вид цільового призначення земель (згідно класифікатору)
  
 $auction_klasifikator = new Admin_Table_Auction_Auctionlots();
 $auction_klasifikator_filters =$auction_klasifikator->setauctionlots();// берем массив с БД
 
 foreach ( $auction_klasifikator_filters as $key => $value) {  // определяем каждый элемент 
          for($u=0; $u<count($data['data']); $u++){            // берем то что было
            if ( $data['data'][$u]['purpose'] ==  $value['auction_klasifikator_num']) // сверяем есть ли такое в базе
                 $data['data'][$u]['purpose'] = $value['auction_klasifikator_txt'];    // делаем замену
             }
    
 } 

#==============================================================================
           
        $lclm->AddData($data);
        
        
        $filters['id_status'] = $this->_table_lots->GetStatusList(@$filters['by_status']);        
        $form->AddData($filters);

        $this->startContent();
        $this->view->xmlWriter->startElement("Main");
        $this->view->assign('List', $lclm->GetList());
        $this->view->assign($form->GetFrom());
        $this->view->xmlWriter->endElement();
        $this->view->xmlWriter->endElement();
    }
    
    public function editAction() {
    	$id = intval($this->_request->getParam('id'));
        if (empty($id)) $this->_redirect('/error/e404');
    	$this->_redirect('/'.$this->controller.'/view/'.$id);
    }

    public function viewAction(){
        $id = intval($this->_request->getParam('id'));
        if (!($id>0)) $this->_redirect('/error/e404');

        $form = new Llib_Form($this->_request);
        //$this->_table_lots = new Admin_Table_Auction_Lots();
        $data = $this->_table_lots->getLotInfo($id);
        
    	if ($this->_request->isPost()) {
    		
    		
            $posted_data = $form->GetPostedData();
            if(!empty($posted_data)){
	            if(isset($posted_data['id_status']) && $posted_data['id_status']>1 && $posted_data['id_status']!=$data['id_status']){
	            	unset($posted_data['id']);                        
                        $auction_status = $this->_table_auction->getStatus($posted_data['id_auction']);
                        //if((isset($auction_status) && $auction_status == 2 && $posted_data['id_status'] == 2) || $posted_data['id_status'] == 3){
                            unset($posted_data['id_auction']);
                            if ($this->_table_lots->update($posted_data, $id, $this->_user->id, $this->_user->role_id)) {
                                    $form->SetSuccess();
                                    //prepare for publish - Перевірено
//                                    if($posted_data['id_status'] == 2){
//                                        $table_GeoDB_parcel_auction = new Admin_Table_Auction_ParcelAuction(Zend_Registry::get('config'));
//                                        $retGeoRowId = $table_GeoDB_parcel_auction->insert(array_merge($data,$this->getDataFromLotXML($id)));
//                                        if(!($retGeoRowId>0)) $form->SetError('Ділянка не була додана до картографічного модулю. Зверніться до адміністратора '.$table_GeoDB_parcel_auction->GetError());
//                                        
//                                    }
                            }else $form->SetError("Ви не можете опубліковати матеріал у зв'язку з тим, що його було відкликано з перевірки");
                        //}else{$form->SetError("Спочатку перевірте і опублікуйте дані аукціона №".$posted_data['id_auction']);}
	            }else $form->SetError("Ви не змінете статус.");
            }
        }
        $data = $this->_table_lots->getLotInfo($id);
        
        if($data['id_status'] == 11){
            $table_attaches = new Admin_Table_Auction_Attaches();
            $add_data = $table_attaches->getVideoFile($id);
            $add_data['video_path'] = $this->_http_files . $add_data['video_path'];
            $data = array_merge($data, $add_data);
        }
        
        $data = array_merge($data, $this->_table_lots->getLotFilesCount($id));
        $idstatus = intval(@$data['id_status']);
        
        //первый параметр устанавливает оператора для выборки списка возможных статусов
        $data['status_list'] = $this->_table_lots->GetStatusListForChange(1, @$data['id_status']);         
         
        if($form->GetError() == 0 && $data['id_status']>10 && $data['is_approved'] != 1 && $data['id_status'] != 15) 
            $form->SetError("Результати торгів не підтвержено і не опубліковано.");
        if($form->GetError() == 0 && $data['is_gone'] == 1 && $data['id_status'] == 2) 
            $form->SetError("Торги відбулися. Матеріали мають бути надані на протязі 5 робочих днів з ".$data['start_date'].".");
        
        $form->AddData($data);

        $this->startContent();
        $this->view->xmlWriter->startElement("Main");
        $this->view->xmlWriter->writeAttribute('id', $id);
        $this->view->assign($form->GetFrom());
        //!!!!!!!!!!!!!!!!!!!!!!
        //Понадобится после определения списка причин для возвращения 
        //changed: AuctionLotsController.php, auction_change_stat.js, view.xls, db_auction_lots(added column:rejectReason)
        //!!!!!!!!!!!!!!!!!!!!!!
        //--------------------------------
        //if($idstatus==1) $this->view->assign('rejectReason',$this->_table_lots->getStatusReasons());
        //--------------------------------
        $this->view->xmlWriter->endElement();
        $this->view->xmlWriter->endElement();
    }
    public function approveAction(){
        $id = intval($this->_request->getParam('id'));
        if (!($id>0)) $this->_redirect('/error/e404');

        $form = new Llib_Form($this->_request);
        $data = $this->_table_lots->getLotInfo($id);
        if($data['id_status'] > 10 && $data['id_status'] < 15)
            $this->_table_lots->update(array('is_approved' => '1'), $id, $this->_user->id, $this->_user->role_id);
        
        $this->_redirect("/" . $this->controller . "/view/" . $id );
    }
    
	public function lotHistoryAction() {
        $id = $this->_request->getParam('id',0);
        $auction_id = $this->_table_lots->getAuctionID($id);
        if (!($id>0)) $this->_redirect('/error/e404');

        $table_history = new Admin_Table_Auction_LotHistory();

        $lclm = new Llib_List($this->_request, $this->_sess);
        $lclm->AddParams(array(
            'checkboxes' => false,
        	'link_fields'=>array('file_name'),
            'link' => "/" . $this->controller . "/lot-history/" . $id . "/"
        ));
        $lclm->AddColumn('Дата', 'add_date', array('width' => '5%', 'sort' => 1));
        $lclm->AddColumn('Користувач', 'user', array('width' => '20%', 'sort' => 0));
        $lclm->AddColumn('Коментар', 'comment', array('width' => '20%', 'sort' => 0));
        $lclm->AddColumn('На статус', 'status', array('width' => '20%', 'sort' => 0));
        $lclm->AddColumn('З причиною', 'reason', array('width' => '35%', 'sort' => 0));
        $lclm->AddData($table_history->getDataList($lclm->page, $lclm->s, $lclm->pager_count, array('id_lot'=>$id)));

        $this->startContent();
        $this->view->xmlWriter->startElement("Main");
        $this->view->xmlWriter->writeAttribute('id', $id);
        $this->view->xmlWriter->writeAttribute('id_auction', $auction_id);
        $this->view->assign('List', $lclm->GetList());
        $this->view->xmlWriter->endElement();
        $this->view->xmlWriter->endElement();
    }

    private function getDataFromLotXML($id){
    	$dataFromXML = array('id_lot'=>$id);
    	$table_exchange_files = new Admin_Table_Auction_ExchangeFile();
        $info = $table_exchange_files->GetDataRow(array('id_lot'=>$id));
        
        if(!empty($info)){
        	$dataFromXML['id_exchange']=$info['ID'];
        	
        	$xml = new Llib_Xml($info['FILE_PATH'].'/'.$info['FILE_NAME']);
        	$parcel_info = $xml->getParcelInfo();
        	
        	$dataFromXML['category'] = intval($parcel_info['CategoryPurposeInfo']['Category']);
        	$dataFromXML['use'] = trim($parcel_info['CategoryPurposeInfo']['Use']);
        	$dataFromXML['ownership_code'] = intval($parcel_info['OwnershipInfo']);
        	$dataFromXML['area_measurement'] = trim($parcel_info['ParcelMetricInfo']['Area']['MeasurementUnit']);
        	
        	$coordinat_info = $xml->getMetricInfo();
        	$dataFromXML['coordsys_code'] = 0;
        	
        	if (!empty($coordinat_info) && isset($coordinat_info['CoordinateSystem'])){
	        	switch ($coordinat_info['CoordinateSystem']) {
	        		case 'SC63':
	        			$dataFromXML['coordsys_code'] = 10630;
	        			break;
	        		case 'SC42':
	        			$dataFromXML['coordsys_code'] = 10426;
	        			break;
	        		case 'SC42_3':
	        			$dataFromXML['coordsys_code'] = 10423;
	        			break;
	        	}
	        	if ($dataFromXML['coordsys_code']>0){
	        		if(isset($coordinat_info['CoordinateSystemZone'])) $dataFromXML['coordsys_code'] .= intval($coordinat_info['CoordinateSystemZone']);
        			else $dataFromXML['coordsys_code'] .= 0;
        			
        			$PPoint = "";
        			$xml = $xml->getSimpleXmlObj();
	        		$MetricInfo = $xml->InfoPart->MetricInfo;      		
            		$ParcelsNode = $xml->InfoPart->CadastralZoneInfo->CadastralQuarters->CadastralQuarterInfo->Parcels->ParcelInfo;
            		
            		$Node = $MetricInfo->PointInfo->Point;
            		if(sizeof($Node)>0){
            			$Points = Array();
            			foreach ($Node as $PointInfo) {
            				$Points[(string)$PointInfo->UIDP] = array('X'=>(string)$PointInfo->X, 'Y'=>(string)$PointInfo->Y);
            			}
	            			
            			if(!empty($Points)){
            				$Node = $MetricInfo->Polyline->PL;
            				if(sizeof($Node)>0){
            					$PL = Array();
	            				foreach ($Node as $PolylineInfo) {
		            				$PL[(string)@$PolylineInfo->ULID] = array();
		            				$P = @$PolylineInfo->Points->P;
		            				if(isset($P) && !empty($P)){
			            				foreach ($P as $v) {
			            					$PL[(string)@$PolylineInfo->ULID][] = (string)$v;
			            				}
		            				}
		            			}
			            			
	            				if(!empty($PL) && !empty($ParcelsNode) && is_object($ParcelsNode)){
	            					$LineNode = @$ParcelsNode->ParcelMetricInfo->Externals->Boundary->Lines->Line;
		            				if(sizeof($LineNode)>0){
		            					$PoligonPoints = Array();
		            					$i = 0;
			            				foreach ($LineNode as $LineTurn) {
			            					foreach ($PL[(int)$LineTurn->ULID] as $v) {
			            						$PoligonPoints[$i] = $Points[$v];
			            						if($PPoint!="") $PPoint .= ",";
			            						$PPoint .= (float) str_ireplace(",",".",$Points[$v]['X'])." ".(float) str_ireplace(",",".",$Points[$v]['Y']);
			            						$i++;
			            					}
				            			}
		            				}
		            			}
            				}
            			}
            		}
        			
        			
        			
        			if($PPoint!=""){
            			$endPoint = end($PoligonPoints);
            			if (!($PoligonPoints[0]['X']==$endPoint['X'] && $PoligonPoints[0]['Y']==$endPoint['Y'])) $PPoint .= ",".(float) str_ireplace(",",".",$PoligonPoints[0]['X'])." ".(float) str_ireplace(",",".",$PoligonPoints[0]['Y']);
        			}
        			unset($xml);
        			$dataFromXML['the_geom']=$PPoint;
	        	}
        	}        	
        }
        return $dataFromXML;
    }
    
    public function fileAttacheAction() {
        $id = intval($this->_request->getParam('id'));
        $auction_id = $this->_table_lots->getAuctionID($id);
        if (empty($id)) $this->_redirect('/error/e404');

        $filters = array();

        if ($this->_request->isPost()) $filters['by_file_type'] = $this->_request->getParam('by_file_type', '');

        $filters = $this->SessionVarsEx($filters, array('by_file_type'), $this->_request->getParam('reset', false));

        $form = new Llib_Form($this->_request);
        $table_attaches = new Admin_Table_Auction_Attaches();
        $data['attache_types'] = $table_attaches->getFileTypes();
        $data = array_merge($data, $table_attaches->getLotFilesCount($id));
        $data = array_merge($data, $filters);
        $form->AddData($data);

        $lclm = new Llib_List($this->_request, $this->_sess);
        $lclm->AddParams(array(
            'checkboxes' => false,
        	//'link_fields'=>array('file_name'),
            'link' => "/" . $this->controller . "/download/" . $id . "/attache/"
        ));
        $lclm->AddColumn('Імя файлу', 'file_name', array('width' => '30%', 'sort' => 1));
        $lclm->AddColumn('Тип файлу', 'file_type', array('width' => '70%', 'sort' => 1));
        $lclm->AddData($table_attaches->getDataList($id, $lclm->page, $lclm->s, $lclm->pager_count, $filters));

        $this->startContent();
        $this->view->xmlWriter->startElement("Main");
        $this->view->xmlWriter->writeAttribute('id', $id);
        $this->view->xmlWriter->writeAttribute('id_auction', $auction_id);
        $this->view->assign('List', $lclm->GetList());
        $this->view->assign($form->GetFrom());
        $this->view->xmlWriter->endElement();
        $this->view->xmlWriter->endElement();
    }

    public function downloadAction() {
        echo 'downloadAction ';
        $id = intval($this->_request->getParam('id'));
        $attache_id = intval($this->_request->getParam('attache'));

        if (empty($id) || empty($attache_id)) $this->_redirect('/error/e404');

        $table_attaches = new Admin_Table_Auction_Attaches();
        $file_data = $table_attaches->getFileData($attache_id);

        if (empty($file_data)) $this->_redirect('/error/e404');
        
        
            
        ignore_user_abort(true);
        set_time_limit(0);

        if (file_exists($this->_path_files . DIRECTORY_SEPARATOR . $file_data['file_path'] . DIRECTORY_SEPARATOR . $file_data['file_name'])) {
            if (preg_match('/Opera(\| )([0-9].[0-9]{1,2})/', $_SERVER['HTTP_USER_AGENT']))
                $UserBrowser = "Opera";
            elseif (preg_match('/MSIE ([0-9].[0-9]{1,2})/', $_SERVER['HTTP_USER_AGENT']))
                $UserBrowser = "IE";
            else
                $UserBrowser = "";

            $mime_type = ($UserBrowser == 'IE' || $UserBrowser == 'Opera') ? 'application/octetstream' : 'application/octet-stream';
            @ob_end_clean();
            
            $tpl = file_get_contents($this->_path_files . DIRECTORY_SEPARATOR . $file_data['file_path'] . DIRECTORY_SEPARATOR . $file_data['file_name']);

            Zend_Controller_Action_HelperBroker::removeHelper('viewRenderer');
            $response = $this->getResponse();
            $response->setBody($tpl)
                    ->setHeader("Content-Type", $mime_type, true)
                    ->setHeader("Content-Transfer-Encoding", "binary", true)
                    ->setHeader("Content-Disposition", "attachment; filename=\"$file_data[file_name]\"", true)
                    ->setHeader("Expires", "0", true);
        }

    }

    private function downloadAttachment($path, $name) {
        ignore_user_abort(true);
        set_time_limit(0);

        if (file_exists($path)) {
            if (preg_match('/Opera(\| )([0-9].[0-9]{1,2})/', $_SERVER['HTTP_USER_AGENT']))
                $UserBrowser = "Opera";
            elseif (preg_match('/MSIE ([0-9].[0-9]{1,2})/', $_SERVER['HTTP_USER_AGENT']))
                $UserBrowser = "IE";
            else
                $UserBrowser = "";

            $mime_type = ($UserBrowser == 'IE' || $UserBrowser == 'Opera') ? 'application/octetstream' : 'application/octet-stream';
            @ob_end_clean();

            header('Content-Type: ' . $mime_type);
            header('Content-Disposition: attachment; filename="' . $name . '"');
            header('Accept-Ranges: bytes');
            header("Cache-control: private");
            header('Pragma: private');
            header("Content-Length: " . filesize($path));

            $fd = fopen($path, "r");
            if ($fd) {
                while (!feof($fd)) {
                    $buffer = fread($fd, 1024 * 128);
                    echo $buffer;
                }
                @ob_flush();
                fclose($fd);
            }
        }
    }

    public function ajaxDistrictsReloadAction() {
    	$this->_table = new Admin_Table_Auction_Auction();
        $id_region = intval(@$_REQUEST['id_region']);

        echo "<option value='0'>-- Не вказано --</option>";

        if (is_numeric($id_region) && !empty($id_region)) {
            $items = $this->_table->addressGetDistricts($id_region);

            if (!empty($items) && is_array($items)) {
                foreach ($items as $value)
                    echo sprintf("<option value='%d'>%s</option>", $value['id'], $value['name']);
            }
        }

        die();
    }

    public function ajaxTownReloadAction() {
    	$this->_table = new Admin_Table_Auction_Auction();
        $id_region = intval(@$_REQUEST['id_region']);
        $id_district = intval(@$_REQUEST['id_district']);

        echo "<option value='0'>-- Не вказано --</option>";

        if (is_numeric($id_region) && !empty($id_region) && is_numeric($id_district) && !empty($id_district)) {
            $items = $this->_table->addressGetTowns($id_region, $id_district);

            if (!empty($items) && is_array($items)) {
                foreach ($items as $value)
                    echo sprintf("<option value='%d'>%s</option>", $value['id'], $value['name']);
            }
        }
        die();
    }

}
